//
//  NewSchedulerViewController.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/12.
//

import UIKit
import BRPickerView

class NewSchedulerViewController: UIViewController {
    var model = ScheduleListModel()
    
    private var imageArr1 = [String]()
    private var imageArr2 = [String]()
    
    private var titleArr = [ScheduleClassModel]()
    private var leftTitleArr = [String]()
    private var rightTitleArr2 = [String]()
    
    private var selectIndex = -1
    private var titleStr = ""
//    private var isAllDay = false
    var startDate = ""
    private var endDate = ""
    
    /// 重复:1=不重复,2=每天,3=每周,4=每月,5=每年
    private var repeatStr = "1"
    /// 警告:1=5分钟前,2=10分钟前,3=15分钟前,4=30分钟前,5=1小时前
    private var warnStr = "2"

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "创建"
        
        addUI()
        getClassData()
    }
    
    private func getClassData() {
        QINetworkManager.requestJson(urlStr: "/Calendar/class", method: .get, parameters: [:]) { json in
             print(json)
            self.titleArr = json.arrayObject?.kj.modelArray(ScheduleClassModel.self) ?? [ScheduleClassModel]()
            self.collectionView.reloadData()
            self.getCalendarData()
        }
    }
    
    private func getCalendarData() {
        guard model.id.count > 0 else {
            return
        }
        QINetworkManager.requestJson(urlStr: "/Calendar/read", method: .get, parameters: ["id": model.id]) { [self] json in
            print(json)
            let model1 = json.dictionaryObject?.kj.model(ScheduleListModel.self) ?? ScheduleListModel()
            
            titleStr = model1.title
            startDate = model1.createtime
            endDate = model1.endtime
//            selectIndex = titleArr.firstIndex(of: model1.class_name) ?? 0
            for (index, model2) in titleArr.enumerated() {
                if model1.class_name == model2.name {
                    selectIndex = index
                }
            }
            
            var warnStr = ""
            //警告:1=5分钟前,2=10分钟前,3=15分钟前,4=30分钟前,5=1小时前
            if model1.warn == "1" {
                warnStr = "5分钟前"
            } else if model1.warn == "2" {
                warnStr = "10分钟前"
            } else if model1.warn == "3" {
                warnStr = "15分钟前"
            } else if model1.warn == "4" {
                warnStr = "30分钟前"
            } else if model1.warn == "5" {
                warnStr = "1小时前"
            }

            rightTitleArr2 = [warnStr]
            imageArr2 = ["时钟"]
            rightTitleArr2 = ["10分钟前"]
            collectionView.reloadData()
            tableView1.reloadData()
            tableView2.reloadData()
        }
    }
   
    private func addUI() {
        
        //titleArr = ["饮食计划", "运动计划", "情绪控制", "月经调节", "备孕", "冻卵准备"]
        imageArr1 = ["请输入标题", "开始", "结束"]
        imageArr2 = ["重置", "时钟"]
        leftTitleArr = ["请输入标题", "开始", "结束"]
        rightTitleArr2 = ["不重复", "10分钟前"]
        self.view.addGradientColor(fromColors: [ColorWithStr("#FFB2B5").cgColor, ColorWithStr("#FCDFE0").cgColor, ColorWithStr("#FFFBFB").cgColor], locationArr: [0, 0.5, 1.0], with: .topToBottom)
        
        view.addSubview(collectionView)
        
        tableView1.frame = CGRect(x: 15, y: collectionView.bottom + 15, width: SCREEN_WIDTH - 30, height: CGFloat(imageArr1.count * 50))
        tableView1.addRoundedCorners(withRadius: 10)
        view.addSubview(tableView1)
        
        tableView2.frame = CGRect(x: 15, y: tableView1.bottom + 15, width: SCREEN_WIDTH - 30, height: 100)
        tableView2.addRoundedCorners(withRadius: 10)
        view.addSubview(tableView2)
        
        let saveBtn = UIButton().then {
            $0.frame = CGRect(x: 15, y: SCREEN_HEIGHT - 68, width: SCREEN_WIDTH - 30, height: 40)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 14)
            $0.setTitle("保存", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 8)
            $0.addTarget(self, action: #selector(saveBtnClick), for: .touchUpInside)
        }
        view.addSubview(saveBtn)
    }
    
    @objc private func saveBtnClick() {
        guard selectIndex > -1 else {
            ShowHUD(str: "请选择类型")
            return
        }
        guard startDate.count > 0 else {
            ShowHUD(str: "请选择开始时间")
            return
        }
        guard endDate.count > 0 else {
            ShowHUD(str: "请选择结束时间")
            return
        }
        guard titleStr.count > 0 else {
            ShowHUD(str: "请输入标题")
            return
        }
         
        let classModel = titleArr[selectIndex]
        var paramete = [
            "title": titleStr,
            "starttime": startDate,//"\(year)-\(startDate):00",
            "endtime": endDate,//"\(year)-\(endDate):00",
            "warn": warnStr,        //警告:1=5分钟前,2=10分钟前,3=15分钟前,4=30分钟前,5=1小时前
            "class_name": classModel.name,
            "color": classModel.color
        ] as [String : Any]
        print(paramete)
        
        if model.id.count > 0 {     //编辑
            paramete["id"] = model.id
            QINetworkManager.requestJson(urlStr: "/Calendar/edit", parameters: paramete) { json in
                print(json)
                ShowHUD(str: "编辑成功")
                self.navigationController?.popViewController(animated: true)
            }
        } else {        //创建
            paramete["repeat"] = repeatStr//重复:1=不重复,2=每天,3=每周,4=每月,5=每年
            QINetworkManager.requestJson(urlStr: "/Calendar/add", parameters: paramete) { json in
                print(json)
                ShowHUD(str: "添加成功")
                self.navigationController?.popViewController(animated: true)
            }
        }
        
    }
    

    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 10
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: 120), collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.register(NewSchedulerViewCell.classForCoder(), forCellWithReuseIdentifier: "NewSchedulerViewCell")
        collectionView.register(UICollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView")
        
        return collectionView
    }()
    
    private lazy var tableView1: UITableView = {
        let tableView = UITableView()
        tableView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 200)
        tableView.backgroundColor = .white
        tableView.delegate = self
        tableView.dataSource = self
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        } else {}
        return tableView
    }()
    
    private lazy var tableView2: UITableView = {
        let tableView = UITableView()
        tableView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 200)
        tableView.backgroundColor = .white
//        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        } else {}
        return tableView
    }()
}

extension NewSchedulerViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 50)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return titleArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewSchedulerViewCell", for: indexPath) as! NewSchedulerViewCell
//        cell.titleStr = titleArr[indexPath.row].name
        cell.model = titleArr[indexPath.row]
        if selectIndex == indexPath.row {
            cell.addBorder(withWidth: 1, borderColor: MainColor)
        } else {
            cell.addBorder(withWidth: 0, borderColor: MainColor)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectIndex = indexPath.row
        collectionView.reloadData()
    }
    
}

extension NewSchedulerViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == tableView1 {
            return imageArr1.count
        } else {
            return imageArr2.count
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        50
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = NewSchedulerTitleViewCell()
        cell.selectionStyle = .none
        if tableView == tableView1 {
            let imageStr = imageArr1[indexPath.row]
            let titleStr = leftTitleArr[indexPath.row]
            cell.imageStr = imageStr
            cell.titleStr = titleStr
            if titleStr == "请输入标题" || titleStr == "全天" {
                cell.accessoryType = .none
                cell.model = model
            } else {
                cell.accessoryType = .disclosureIndicator
            }
            
            cell.titleBlock = { str in
                self.titleStr = str
            }
//            cell.switchStatus = { isOn in
//                self.isAllDay = isOn
//            }
            if titleStr == "开始" {
                cell.rightStr = startDate
            } else if titleStr == "结束" {
                cell.rightStr = endDate
            }
        } else {
            let imageStr = imageArr2[indexPath.row]
            cell.imageStr = imageStr
            
            let rightStr = rightTitleArr2[indexPath.row]
            if rightStr.count > 0 {
                cell.titleStr = rightStr
            } else {
                
            }
            cell.accessoryType = .disclosureIndicator
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == tableView1 {
            let titleStr = leftTitleArr[indexPath.row]
            if titleStr == "开始" || titleStr == "结束" {
                let dateView = BRDatePickerView()
                dateView.pickerMode = .YMDHM
                dateView.title = titleStr == "开始" ? "开始日期" : "结束日期"
                dateView.resultBlock = {selectDate, selectValue in
                    print(selectValue ?? "")
                    if titleStr == "开始" {
                        self.startDate = "\(selectValue ?? ""):00"
                    } else {
                        self.endDate = "\(selectValue ?? ""):00"
                    }
                    tableView.reloadRows(at: [indexPath], with: .none)
                }
                dateView.show()
            }
        } else {
            let imgName = imageArr2[indexPath.row]
            if imgName == "重置" {
                let stringPickerView = BRStringPickerView(pickerMode: .componentSingle)
                stringPickerView.title = ""
                stringPickerView.dataSourceArr = ["不重复", "每天", "每周", "每月"]
                stringPickerView.resultModelBlock = {resultModel in
                    print(resultModel?.value ?? "")
                    self.rightTitleArr2[0] = resultModel?.value ?? ""
                    self.repeatStr = "\(resultModel!.index + 1)"
                    tableView.reloadData()
                }
                stringPickerView.show()
            } else if imgName == "时钟" {
                let stringPickerView = BRStringPickerView(pickerMode: .componentSingle)
                stringPickerView.title = ""
                stringPickerView.dataSourceArr = ["5分钟前", "10分钟前", "15分钟前", "30分钟前","1小时前"]
                stringPickerView.resultModelBlock = {resultModel in
                    print(resultModel?.value ?? "")
                    if self.model.id.count > 0 {
                        self.rightTitleArr2[0] = resultModel?.value ?? ""
                    } else {
                        self.rightTitleArr2[1] = resultModel?.value ?? ""
                    }
                    self.warnStr = "\(resultModel!.index + 1)"
                    tableView.reloadData()
                }
                stringPickerView.show()
            }
        }
         
    }
    
}


class NewSchedulerTitleViewCell: UITableViewCell {
    
    var switchStatus: boolBlock?
    var titleBlock: stringBlock?
    private var leftImgView = UIImageView()
    private var leftTitleL = UILabel()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addUI()
    }
    func addUI() {
        
        leftImgView = UIImageView().then {
            $0.frame = CGRect(x: 15, y: 15, width: 20, height: 20)
            $0.image = UIImage(named: "")
        }
        contentView.addSubview(leftImgView)
        
        leftTitleL = UILabel().then({
            $0.frame = CGRect(x: leftImgView.right + 10, y: 0, width: 100, height: 50)
            $0.text = ""
            $0.textColor = Color666666
            $0.font = SYSFONT(ofSize: 14)
        })
        contentView.addSubview(leftTitleL)
        
    }
    
    @objc private func titleTextFClick(textF: UITextField) {
        if titleBlock != nil {
            titleBlock!(textF.text ?? "")
        }
    }
    @objc private func switchBtnClick() {
        if switchStatus != nil {
            switchStatus!(switchBtn.isOn)
        }
    }
    
    var titleStr = "" {
        didSet {
            leftTitleL.text = titleStr
            if titleStr == "请输入标题" {
                leftTitleL.isHidden = true
                titleTextF.isHidden = false
                contentView.addSubview(titleTextF)
            } else if titleStr == "全天" {
                contentView.addSubview(switchBtn)
            } else if titleStr == "开始" || titleStr == "结束" {
                rightL.isHidden = false
                contentView.addSubview(rightL)
            }
        }
    }
    var imageStr = "" {
        didSet {
            leftImgView.image = UIImage(named: imageStr)
        }
    }
    var rightStr = "" {
        didSet {
            rightL.text = rightStr
        }
    }
    var model = ScheduleListModel() {
        didSet {
            if model.id.count > 0 {
                titleTextF.text = model.title
            }
        }
    }
    
    private lazy var rightL: UILabel = {
        let rightL = UILabel().then({
            $0.frame = CGRect(x: self.width - 200, y: 0, width: 200, height: 50)
            $0.text = ""
            $0.textAlignment = .right
            $0.textColor = Color999999
            $0.font = SYSFONT(ofSize: 14)
            $0.isHidden = true
        })
        return rightL
    }()
    private lazy var titleTextF: UITextField = {
        let titleTextF = UITextField().then {
            $0.frame = CGRect(x: leftTitleL.left, y: 0, width: 200, height: 50)
            $0.font = SYSFONT(ofSize: 14)
            $0.placeholder = "请输入标题"
            $0.isHidden = true
            $0.addTarget(self, action: #selector(titleTextFClick(textF: )), for: .editingChanged)
        }
        return titleTextF
    }()
    private lazy var switchBtn: UISwitch = {
        let switchBtn = UISwitch(frame: CGRect(x: self.width - 34, y: 10, width: 44, height: 24))
        switchBtn.onTintColor = MainColor
        switchBtn.addTarget(self, action: #selector(switchBtnClick), for: .touchUpInside)
        return switchBtn
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}



